<?php
session_start();
include_once("../../untils/conn.php");
mysqli_query($con, "set names utf8");

// 获取当前正在登录的账号信息的代理
$proxy_acc = $_SESSION["account"];

// 防止 SQL 注入攻击
$proxy_acc = mysqli_real_escape_string($con, $proxy_acc);

// 查询proxy表，找到符合条件的数据并输出给前端
$sql = "SELECT * FROM proxy WHERE proxy_acc = '$proxy_acc'";
$result = mysqli_query($con, $sql);

if ($result) {
  $rows = mysqli_fetch_assoc($result);
  $id = $rows["proxy_id"];

  // 查询oder表，找到符合条件的数据并计算行数
  $sql = "SELECT COUNT(*) AS count FROM oder WHERE proxy_id = '$id'";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $row = mysqli_fetch_assoc($result);
    $count = $row['count'];
  } else {
    $count = 0;
  }

  // 查询proxy表，找到符合条件的数据并输出给前端
  $sql = "SELECT proxy_balance FROM proxy WHERE proxy_id = '$id'";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $row = mysqli_fetch_assoc($result);
    $balance = $row['proxy_balance'];
  } else {
    $balance = 0;
  }

  // 查询list表，找到符合条件的数据并计算行数
  $sql = "SELECT COUNT(*) AS counts FROM list";
  $result = mysqli_query($con, $sql);
  if ($result) {
    $row = mysqli_fetch_assoc($result);
    $list = $row['counts'];
  } else {
    $list = 0;
  }
  
// 查询revenue表，找到符合条件的数据并计算总和
$sql = "SELECT SUM(price) AS total FROM revenue WHERE oder_sta = '3' AND account = '$proxy_acc' AND type = 0";
$result = mysqli_query($con, $sql);
if ($result) {
  $row = mysqli_fetch_assoc($result);
  $revenue = $row['total'];
} else {
  $revenue = 0;
}


// 查询oder表，找到符合条件的数据并计算百分比
$sql = "SELECT COUNT(*) AS total, SUM(CASE WHEN card_sta = 0 THEN 1 ELSE 0 END) AS inactive, SUM(CASE WHEN card_sta = 1 THEN 1 ELSE 0 END) AS active FROM oder WHERE proxy_id = '$id'";
$result = mysqli_query($con, $sql);
if ($result) {
  $row = mysqli_fetch_assoc($result);
  $total = $row['total'];
  $inactive = $row['inactive'];
  $active = $row['active'];
  $inactive_percentage = $total == 0 ? 0 : round($inactive / $total * 100, 2);
  $active_percentage = $total == 0 ? 0 : round($active / $total * 100, 2);
} else {
  $total = 0;
  $inactive = 0;
  $active = 0;
  $inactive_percentage = 0;
  $active_percentage = 0;
}


//   echo $beizhu = "订单数:" . $count . "产品数：" . $list ."代理余额：". $balance . "预估佣金：".$revenue . "未激活：". $inactive_percentage. "已激活：".$active_percentage ; 

// 将变量存储到关联数组中
$data = array(
  "count" => $count,
  "balance" => $balance,
  "list" => $list,
  "revenue" => $revenue,
  "inactive" => $inactive,
  "active" => $active,
  "inactive_percentage" => $inactive_percentage,
  "active_percentage" => $active_percentage
);

// 将关联数组转换为 JSON 格式并输出
echo json_encode($data);

} else {
//   echo "查询出错！";
}
